(function(window,angular){
	'use strict';
    (function(){
        'use strict';
        angular.module('ngModuleInstaller',['ng'])
		.provider('$moduleInstaller', function(){
			this.$get = ['$filter', '$translate', '$rootScope',
				function($filter, $translate, $rootScope){
					var $moduleInstaller = {status:{msg : '', is_complete: true}},
					    module_content = {root_path: '', zip_name: 'module_update.zip'};
					//Module update(content = {version[模組現有版本], callback[更新成功], errorback[更新失敗]})
					$moduleInstaller.update = function(content){
						$moduleInstaller.status.is_complete = false;
						$moduleInstaller.status.msg = '';

						module_content.root_path = content.root_path||module_content.root_path;
						module_content.zip_name = content.zip_name||module_content.zip_name;
						if(content.url != ''){
							//need update
							if(window.cordova){
								downloadZIP_cordova(content.url, function(){
									if(content.callback)
										content.callback();
								}, function(){
									if(content.errorback){
										content.errorback();
									}
								});
							} else if(window.nodeRequire){
								downloadZIP_electron(content.url, function(){
									if(content.callback)
										content.callback();
								}, function(){
									if(content.errorback){
										content.errorback();
									}
								});
							} else {
								content.callback();
							}
						} else {
							//don't need update
							if(content.callback)
								content.callback();
						}
					}

					//App platform download ZIP File
					function downloadZIP_cordova(url, callback, errorback){
						var zipDistUrl = cordova.file.dataDirectory;
						var ft = new FileTransfer();
						ft.onprogress = function(progressEvent) {
							if (progressEvent.lengthComputable) {
								//更新下載中
								$moduleInstaller.status.msg = $filter('translate')('update.msg.update_downloading')+Math.floor(progressEvent.loaded / progressEvent.total * 100)+'%';
								$rootScope.$apply();
							}
						};
						ft.download(url, zipDistUrl+'//'+module_content.zip_name,
							function(r) {
								$moduleInstaller.status.msg = $filter('translate')('update.msg.updating');//程式更新中...
								//$rootScope.$apply();
								ExtractZIP_Cordova(zipDistUrl, callback, errorback);
							}, function(error) {
								$moduleInstaller.status.msg = $filter('translate')('update.msg.cant_download');//無法下載更新，請確認伺服器連線是否正常;
								//$rootScope.$apply();
								if(errorback)
									errorback(error);
							}
						);
					}

					//App Android platform extract ZIP File
					function ExtractZIP_Cordova(zipDistUrl, callback, errorback){
						$moduleInstaller.status.msg = $filter('translate')('update.msg.updating');//程式更新中...
						//$rootScope.$apply();
						var dstDir = zipDistUrl + 'update//'+module_content.root_path;
						zip.unzip(zipDistUrl + module_content.zip_name, dstDir,
							function(result){
								if(result==0){
									clearUpdate(zipDistUrl, module_content.zip_name, function(){
										if(callback)
											callback();
									});
								} else {
									$moduleInstaller.status.msg = $filter('translate')('update.msg.zip_server_connect');//'更新檔解析失敗，請重新下載';
									//$rootScope.$apply();
									if(errorback)
										errorback();
								}
							},
							function(progressEvent){
								$moduleInstaller.status.msg = $filter('translate')('update.msg.updating') + Math.round((progressEvent.loaded / progressEvent.total) * 100)+'%';
								//$rootScope.$apply();
							}
						);
					}

					//Desktop platform download ZIP File and extract zip
					function downloadZIP_electron(url, callback, errorback){
						var data = {
							url : url,
							method : 'GET',
							type:"application/octet-stream",
							responseType: 'arraybuffer'
						};
						var request = nodeRequire('request');
						var progress = nodeRequire('request-progress');
						var fs = nodeRequire('fs');

						$moduleInstaller.status.msg = $filter('translate')('update.msg.updating');
						//$rootScope.$apply();
						var Zip = nodeRequire('adm-zip-electron');
						var AppPath;
						if(nodeRequire('electron')){
							AppPath = nodeRequire('electron').remote.app.getAppPath()+'\\';
						} else {
							var nwDir = nodeRequire('path').dirname(process.execPath);
							AppPath = nwDir+'\\package.nw\\';
						}

						var updateFile = AppPath + module_content.zip_name;//zip檔下載位置
						var tempFile = fs.createWriteStream(updateFile);
						tempFile.on('finish', function(){
							tempFile.close(function(){
								try{
									$moduleInstaller.status.msg = $filter('translate')('update.msg.updating');//程式更新中...
									//$rootScope.$apply();
									var zip = new Zip(updateFile);
									zip.extractAllTo(AppPath+'www\\'+module_content.root_path+'\\', true);
									clearUpdate(AppPath, module_content.zip_name, callback);
								}catch(e){
									$moduleInstaller.status.msg = $filter('translate')('update.msg.zip_cant_download')+'<br>'+e;//無法下載更新，更新用的檔案不存在，請確認伺服器連線資訊是否正確
									//$rootScope.$apply();
									if(errorback)
										errorback(e);
								}
							});
						});
						var request = request(url, function(error, response, body){
							if(error){
								$moduleInstaller.status.msg = $filter('translate')('update.msg.zip_cant_download')+'<br>'+error;//無法下載更新，更新用的檔案不存在，請確認伺服器連線資訊是否正確
								//$rootScope.$apply();
								if(errorback)
									errorback(error);
							} else {
								$moduleInstaller.status.msg = $filter('translate')('update.msg.update_downloading')+'100%';
								//$rootScope.$apply();
							}
						});
						request.pipe(tempFile);
						progress(request, {throttle: 200})
						.on('progress', function (state) {
							//更新下載中
							$moduleInstaller.status.msg = $filter('translate')('update.msg.update_downloading')+
							(Math.round(state.percent * 100))+'%';
							$rootScope.$apply();
						})
						.on('error', function (err) {
							$moduleInstaller.status.msg = $filter('translate')('update.msg.zip_cant_download')+'<br>'+err;//無法下載更新，更新用的檔案不存在，請確認伺服器連線資訊是否正確
							//$rootScope.$apply();
							if(errorback)
								errorback(err);
						});
					}

					//delete sJDS\\update.zip file
					function clearUpdate(url, fileName, feedback){
						try{
							window.resolveLocalFileSystemURL(url, function(dir) {
								dir.getFile(fileName, {create:false}, function(fileEntry) {
									fileEntry.remove(function(){
										if(feedback)
											feedback();
										// The file has been removed succesfully
									},function(error){
										$moduleInstaller.status.msg = $filter('translate')('update.msg.temp_file_cant_dele');//暫存檔案刪除失敗
										//$rootScope.$apply();
										if(feedback)
											feedback();
									},function(){
										$moduleInstaller.status.msg = $filter('translate')('update.msg.temp_file_not_exist');//暫存檔案不存在
										//$rootScope.$apply();
										if(feedback)
											feedback();
									});
								});
							});
						} catch(e){
							nodeRequire('fs').unlink(url+'\\'+fileName, function(error){
								if(feedback)
									feedback();
							});
						}
					}
					return $moduleInstaller;
				}
			];
		});
	})();

 })(window, window.angular);
